package cn.baage.campus.config.security.handler;

import cn.baage.campus.enums.ExceptionType;
import cn.baage.campus.utils.ResultUtils;
import cn.baage.campus.utils.Result;
import com.alibaba.fastjson2.JSON;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.web.access.AccessDeniedHandler;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @Description: 权限异常处理器
 * @Author: 八阿哥
 * @url: baage.cn
 * @Version: 1.0
 **/
@Component
@Slf4j
public class RestAccessDeniedHandler implements AccessDeniedHandler {
    @Override
    public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException accessDeniedException) throws IOException {
        log.debug("权限错误：{}", accessDeniedException.getMessage());
        ExceptionType accessDeniedError = ExceptionType.ACCESS_DENIED_ERROR;
        Result<Object> result = Result.fail(accessDeniedError.getErrorCode(), accessDeniedError.getErrorMessage());
        String jsonString = JSON.toJSONString(result);
        ResultUtils.renderString(response, jsonString);
    }
}